#include "omrenderer.h"
#include <QGLWidget>
#include "canves/omglcanves.h"
#include "document/omdocument.h"

OMRenderer::OMRenderer()
        : mDocument(0)
        , mTextureId(0)
        , mCanves(0)
        , mScaleFactor(1.0)
{
}

void OMRenderer::setDocument(OMDocument* document)
{
    mDocument = document;
}

OMDocument* OMRenderer::document(void)
{
    return mDocument;
}

void OMRenderer::setCanves(OMGLCanves* canves)
{
    mCanves = canves;
}

void OMRenderer::renderDocument(void)
{
    glClear(GL_COLOR_BUFFER_BIT);

    if(0 == mCanves || 0 == mTextureId)
        return;

    QPixmap* sCodePixmap = mDocument->securityCodePixmap();
    if(0 == sCodePixmap)
        return;

    // mCanves->drawTexture(QRectF(0, 0, sCodePixmap->width(), sCodePixmap->height()), mTextureId);
    // mCanves->drawTexture(QPointF(0, 0), mTextureId);
    glMatrixMode(GL_MODELVIEW);

    glEnable(GL_TEXTURE_2D);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);

    glPushMatrix();
    glBegin(GL_QUADS);
        glColor3f(1.0f, 1.0f, 1.0f);

        for(int w = 0; w < sCodePixmap->height(); w++)
            for(int h = 0; h < sCodePixmap->width(); h++)
            {
                double tU = h*1.0 / sCodePixmap->height();
                double tV = w*1.0 / sCodePixmap->width();

                glNormal3d(0.0, 0.0, 1.0);
                glTexCoord2d(tU, tV);
                glVertex2d(h * mScaleFactor, w * mScaleFactor);
                glNormal3d(0.0, 0.0, 1.0);
                glTexCoord2d(tU, tV);
                glVertex2d((h+1) * mScaleFactor, w * mScaleFactor);
                glNormal3d(0.0, 0.0, 1.0);
                glTexCoord2d(tU, tV);
                glVertex2d((h+1) * mScaleFactor, (w+1) * mScaleFactor);
                glNormal3d(0.0, 0.0, 1.0);
                glTexCoord2d(tU, tV);
                glVertex2d(h * mScaleFactor, (w+1) * mScaleFactor);
            }
    glEnd();
    glPopMatrix();
}

void OMRenderer::resetScene(void)
{
    if(0 != mTextureId)
        freeTexture();

    mTextureId = mCanves->bindTexture(*(mDocument->securityCodePixmap()));
}

void OMRenderer::freeTexture(void)
{
    mCanves->deleteTexture(mTextureId);
}
